/**
 * 
 */
package hihocoder;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

/**
 * @author zhongfang
 *
 */
public class 同步H公司的终端 {

	static class Node{
		int val;
		ArrayList<Node> childs=new ArrayList<>();
	}
	static long addTotal=0;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int N=scanner.nextInt();
		Node[] nodes=new Node[N+1];
		HashSet<Integer> roots=new HashSet<>(N);
		for (int i = 1; i <=N; i++) {
			nodes[i]=new Node();
			nodes[i].val=scanner.nextInt();
			roots.add(i);
		}
		for (int i = 0; i < N-1; i++) {
			int a=scanner.nextInt();
			int b=scanner.nextInt();
			nodes[a].childs.add(nodes[b]);
			roots.remove(b);//b不可能是根节点
		}
		scanner.close();
		Node root=null;
		for (Integer integer : roots) {
			root=nodes[integer];
		}
		getMinSum(root);
		System.out.println(addTotal);
	}
	private static long getMinSum(Node root) {
		ArrayList<Node> childs=root.childs;
		long[] sums=new long[childs.size()];
		long max=0;
		for (int i = 0; i < sums.length; i++) {
			sums[i]=getMinSum(childs.get(i));
			max=Math.max(sums[i], max);
		}
		for (int i = 0; i < sums.length; i++) {
			if(sums[i]!=max){
				addTotal+=(max-sums[i]);
			}
		}
		max+=root.val;
		return max;
	}
}
